package jehc.djshi.file.util;

import jehc.djshi.common.base.BaseService;
import jehc.djshi.common.entity.UploadEntity;
import jehc.djshi.common.util.AllUtils;
import jehc.djshi.common.util.ExceptionUtil;
import jehc.djshi.common.util.date.DateUtil;
import jehc.djshi.common.util.file.FileUtil;
import jehc.djshi.file.config.MinioConfig;
import jehc.djshi.file.model.XtAttachment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc 附件管理
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Service
public class FileService extends BaseService{

    @Autowired
    MinIOUtil minIOUtil;

    @Autowired
    MinioConfig minioConfig;

    /**
     * 通用文件上传
     * @param uploadEntity
     * @param path 上传的路径
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public List<XtAttachment> upLoad(UploadEntity uploadEntity, List<MultipartFile> multipartFileList, String path) throws IllegalStateException, IOException{
        List<XtAttachment> list = new ArrayList<XtAttachment>();
        File filePath = new File(path);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        String relative_path = uploadEntity.getXt_path_relativek();
        String validateparameter = uploadEntity.getValidateparameter();
        String validateSize = uploadEntity.getValidateSize();
        String xt_path_absolutek = uploadEntity.getXt_path_absolutek();
        String xt_path_relativek =uploadEntity.getXt_path_relativek();
        String xt_path_urlk = uploadEntity.getXt_path_urlk();
        //先判断request中是否包涵multipart类型的数据，
        if (null != multipartFileList && multipartFileList.size() > 0 ) {
            for(MultipartFile file : multipartFileList){
                if(file != null){
                    //验证图片类型 验证图片大小
                    if(validate(file,validateparameter,validateSize)){
                        String fileName = file.getOriginalFilename();
                        int lastD = fileName.lastIndexOf('.');
                        String newName = AllUtils.getRandom()+fileName.substring(lastD,fileName.length());

                        /*
                        方案一.采用MinIO模式上传
                        */
                        try {
                            minIOUtil.putObject(minioConfig.getBucketName(),newName,file.getInputStream(),file.getContentType());
                        }catch (Exception e){
                            throw new ExceptionUtil("上传文件至MinIO服务异常",e.getCause());
                        }

                        /*
                        方案二.采用文件拷贝模式上传
                        //写文件到本地
                        //File localFile = new File(path);
                        //file.transferTo(localFile);
                        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName));//采用文件拷贝模式上传
                        */
                        /* 方案三.FTP模式
//						FtpUtil.uploadFile(path, newName, file.getInputStream());//此处可以修改成Ftp操作如下:

                        */
                        XtAttachment xtAttachment = new XtAttachment();
                        xtAttachment.setXt_attachment_id(toUUID());
                        xtAttachment.setXt_attachmentCtime(DateUtil.getSimpleDateFormat());
                        xtAttachment.setXt_attachmentName(newName);
                        xtAttachment.setXt_attachmentPath(relative_path+newName);
                        xtAttachment.setXt_attachmentSize(""+file.getSize());
                        xtAttachment.setXt_attachmentType(file.getContentType());
                        xtAttachment.setXt_attachmentTitle(fileName);
                        xtAttachment.setXt_userinfo_id(getXtUid());
                        xtAttachment.setXt_path_absolutek(xt_path_absolutek);
                        xtAttachment.setXt_path_relativek(xt_path_relativek);
                        xtAttachment.setXt_path_urlk(xt_path_urlk);
                        list.add(xtAttachment);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 验证文件合法
     * @param file
     * @param validateparameter 格式如:png,jpg,bmp 以逗号分隔
     * @param validateSize 格式如:1024-10240以-分隔
     * @return
     */
    public static boolean validate(MultipartFile file,String validateparameter,String validateSize){
        if(null != validateparameter && !"".equals(validateparameter) && !StringUtils.isEmpty(validateparameter)){
            String[] v = validateparameter.split(",");
            String ftype = FileUtil.getFilePreFix(file.getOriginalFilename()).toLowerCase();
            int flag=0;
            for(int i = 0; i < v.length; i++){
                if(ftype.equals(v[i].toLowerCase())){
                    flag++;
                }
            }
            if(flag==0){
                throw new ExceptionUtil("文件类型不合法：文件只能上传["+validateparameter+"]格式");
            }
        }
        if(null != validateSize && !"".equals(validateSize) && !StringUtils.isEmpty(validateSize)){
            String[] siz = validateSize.split("-");
            long fsize = file.getSize();
            //说明只有一个参数 此时平台默认上传不超过该大小
            if(siz.length==1){
                if(fsize>new Long(siz[0])){
                    throw new ExceptionUtil("文件大小不合法：文件大小不能超过["+siz[0]+"]Kb");
                }
            }else if(siz.length>2 || siz.length < 1){
                throw new ExceptionUtil("文件大小验证规则不符合：请参考格式如:1024-10240以-分隔");
            }else{
                if(fsize < new Long(siz[0])){
                    throw new ExceptionUtil("文件大小不合法：文件大小最小必须超过["+siz[0]+"]Kb");
                }
                if(fsize > new Long(siz[1])){
                    throw new ExceptionUtil("文件大小不合法：文件大小不能超过["+siz[1]+"]Kb");
                }
            }
        }
        return true;
    }
}
